<?php

namespace app\common\library;

use think\Config;
use think\Env;
use think\Log;

/**
 * 实名验证
 */
class CheckID
{
    public static function CheckNameAndID($name, $IDCard)
    {
        $ret = [
            'code' => 0,
            'msg'  => '核验一致'
        ];
        $secretId = Env::get('tencent.market_secret_id');
        $secretKey = Env::get('tencent.market_secret_key');
        $url = Env::get('tencent.market_endpoint');

        $source = 'market';

        // 签名
        $datetime = gmdate('D, d M Y H:i:s T');
        $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
        $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
        $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);

        // 请求方法
        $method = 'POST';
        // 请求头
        $headers = array(
            'X-Source' => $source,
            'X-Date' => $datetime,
            'Authorization' => $auth,
            
        );
        // 查询参数
        $queryParams = array (

        );
        // body参数（POST方法下）
        $bodyParams = array (
            'idcard' => $IDCard,
            'name' => $name,
        );
        // url参数拼接
        if (count($queryParams) > 0) {
            $url .= '?' . http_build_query($queryParams);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
            return $k . ': ' . $v;
        }, array_values($headers), array_keys($headers)));
        if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
        }

        $data = curl_exec($ch);
        if (curl_errno($ch)) {
            Log::write("Error: " . curl_error($ch), 'error');
        } else {
            Log::write("CheckID =>" . $data, 'info');
        }
        curl_close($ch);
        $json = json_decode($data, true);
        if (empty($json['code'])) {
            Log::write("CheckID => 返回结构错误", 'error');
            $ret['code'] = -1;
            $ret['msg'] = '系统错误';
        } else if ($json['code'] == 200){
            if ($json['data']['result'] != 1) {
                $ret['code'] = -1;
                $ret['msg'] = $json['data']['message'];
            }
        } else {
            $ret['code'] = -1;
            $ret['msg'] = $json['msg'];
            Log::write("CheckID => 接口返回错误" . $json['msg'], 'error');
        }

        return $ret;
    }

}
